<?php

namespace app\admin\controller;

use app\admin\model\User;
use app\common\library\AipFace;
use app\common\model;

use app\common\controller\Backend;
use app\common\library\Auth;
use Endroid\QrCode\QrCode;
use fast\Http;
use fast\Pinyin;
use fast\Random;
use GuzzleHttp\Client;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Log;
use think\Validate;
use app\admin\library\DistinguishAddress;

/**
 * 学生
 *
 * Class Student
 * @package app\admin\controller
 */
class Student extends Backend
{
    /**
     * @var \app\common\model\Student
     */
    protected $model = null;
    protected $searchFields = 'name';
    protected $noNeedRight = ['download'];
    protected $schoolLimit = true;
    protected $modelValidate = true;
    protected $modelSceneValidate = true;
    protected $genderData = [];
    protected $relationSearch = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Student');

        $this->genderData = model\User::getGenderList();
        $this->view->assign('genderData', $this->genderData);
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            if ($class_id = $this->request->request('class_id')) {
                $this->model->where('class_id', $class_id);
            }

            $total = $this->model
                ->alias('student')
                ->with('school')
                ->with('grade')
                ->with('classes')
                ->join('__PARENTS__ parents', 'parents.id = student.parents_id', 'left')
                ->join('__USER__ user', 'user.id = parents.user_id', 'left')
                ->where($where)
                ->count();

            if ($class_id = $this->request->request('class_id')) {
                $this->model->where('class_id', $class_id);
            }

            $list = $this->model
                ->alias('student')
                ->with('school')
                ->with('grade')
                ->with('classes')
                ->join('__PARENTS__ parents', 'parents.id = student.parents_id', 'left')
                ->join('__USER__ user', 'user.id = parents.user_id', 'left')
                ->where($where)
                ->field('student.*,user.nickname parents_name,user.mobile parents_mobile')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            if ($list) {
                foreach ($list as $key => $value) {
                    $list[$key]['gender_text'] = \app\common\model\User::getGender($value['gender']);
                    $content = base64_encode(json_encode(['type' => 'student', 'id' => $value['id']]));
                    $qrCode = new QrCode($content);
                    $list[$key]['qrcode'] = $qrCode->getDataUri();
                    $list[$key]["0"] = true;
                }
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                if ($this->schoolLimit && $this->schoolLimitFieldAutoFill) {
                    $params[$this->schoolLimitField] = $this->auth->school_id;
                }

                if (!isset($params['class_id'])) {
                    $this->error('请选择班级');
                }

                $parents_name = $this->request->post("parents_name");
                $parents_mobile = $this->request->post("parents_mobile");

                if (!$parents_mobile || !$parents_name) {
                    $this->error('请填写家长信息');
                }

                if (!Validate::regex($parents_mobile, "^1\d{10}$")) {
                    $this->error('手机号格式不正确');
                }

                $user = model\User::where('username', $params['number'])->count();
                if ($user) {
                    $this->error('学号已存在');
                }

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $params['pinyin'] = Pinyin::get($params['name']);

                    $user = model\User::getUser($parents_mobile, $parents_name, ['school_id' => $this->auth->school_id]);
                    if (isset($user['error'])) {
                        $this->error($user['error']);
                    }

                    $parents = model\Parents::where('user_id', $user->id)->find();
                    if (!$parents) {
                        $parents = new model\Parents();
                        $parents->user_id = $user->id;
                        $parents->school_id = $params['school_id'];
                        $parents->school_id = $this->auth->school_id;
                        $parents->save();
                    }

                    $params['parents_id'] = $parents->id;

                    $student_user = model\User::createUser($params['number'], $params['name'], ['avatar' => $params['avatar'], 'gender' => $params['gender'], 'school_id' => $this->auth->school_id]);
                    if (isset($student_user['error'])) {
                        $this->error($student_user['error']);
                    }

                    $params['user_id'] = $student_user->id;

                    $result = $this->model->allowField(true)->save($params);

                    $classStudent = new model\ClassStudent();
                    $classStudent->class_id = $params['class_id'];
                    $classStudent->student_id = $this->model->id;
                    $classStudent->save();

                    $image = config('app_url') . $params['avatar'];

                    $image_type = 'URL';
                    $group_id = 'mp';
                    $user_id = $student_user->id;
                    $options = array();
                    $options["user_info"] = json_encode(['user_id' => $user_id, 'role' => 'student', 'student_id' =>  $this->model->id]);
                    $options["action_type"] = "REPLACE";
                    $ret = AipFace::instance()->addUser($image, $image_type, $group_id, $user_id, $options);
                    if ($ret['error_code']) {
                        Db::rollback();
                        $this->error($ret['error_msg']);
                    }
                    \app\common\model\User::where('id', $user_id)->update(['face_token' => $ret['result']['face_token']]);

                    $client = new Client([
                        'base_uri' => config('suzhi.url'),
                        'timeout' => 30,
                        'allow_redirects' => true
                    ]);
                    $response = $client->request('POST', '/platform/student/add', [
                        'form_params' => [
                            'id' => $this->model->id,
                            'name' => $params['name'],
                            'avatar' => config('app_url') . $params['avatar'],
                            'class_id' => $params['class_id'],
                            'parent_id' => $user->id,
                            'parent_mobile' => $user->mobile,
                            'parent_name' => $user->nickname,
                        ]
                    ]);
                    $response->getStatusCode();

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model
            ->alias('student')
            ->join('__PARENTS__ parents', 'parents.id = student.parents_id', 'left')
            ->join('__USER__ user', 'user.id = parents.user_id', 'left')
            ->where('student.id', $ids)
            ->field('student.*,user.nickname parents_name,user.mobile parents_mobile')
            ->find();

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $schoolIds = $this->getDataLimitSchoolIds();
        if (is_array($schoolIds)) {
            if (!in_array($row[$this->schoolLimitField], $schoolIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                $parents_name = $this->request->post("parents_name");
                $parents_mobile = $this->request->post("parents_mobile");

                $student_user = [];
                if ($row['user_id']) {
                    $student_user = model\User::where('id', $row['user_id'])->find();
                }

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    if (isset($row['parents_mobile']) && $row['parents_mobile']) {
                        $user = model\User::getUser($row['parents_mobile'], $row['parents_name'], ['school_id' => $row['school_id']]);
                        if (isset($user['error'])) {
                            $this->error($user['error']);
                        }
                        $user->save([
                            'mobile' => $parents_mobile,
                            'username' => $parents_mobile,
                            'nickname' => $parents_name,
                        ]);
                    } else if ($parents_name && $parents_mobile) {
                        $user = model\User::getUser($parents_mobile, $parents_name, ['school_id' => $row['school_id']]);
                        if (isset($user['error'])) {
                            $this->error($user['error']);
                        }
                        $parents = model\Parents::where('user_id', $user->id)->find();
                        if (!$parents) {
                            $parents = new model\Parents();
                            $parents->user_id = $user->id;
                            $parents->school_id = $params['school_id'];
                            $parents->school_id = $this->auth->school_id;
                            $parents->save();
                        }

                        $params['parents_id'] = $parents->id;
                    }

                    $is_update_face = false; // 是否更新人脸库

                    // 该学生是否有 user 用户
                    if ($student_user) {
                        $is_update_user = false; // 是否更新 user 信息

                        // 学号是否有改动
                        if ($params['number'] != $row['number']) {
                            $is_update_user = true;
                            $student_user->username = $params['number'];
                            $student_user->nickname = $params['name'];
                            $username_len = strlen($params['number']);
                            if ($username_len >= 6) {
                                $password = substr($params['number'], $username_len - 6, 6);
                            } else {
                                $password = $params['number'];
                            }
                            $student_user->salt = Random::alnum();
                            $student_user->password = \app\common\library\Auth::instance()->getEncryptPassword($password, $student_user->salt);
                        }

                        // 头像是否有改动
                        if ($params['avatar'] != $row['avatar']) {
                            $is_update_user = true;
                            $is_update_face = true;
                            $student_user->avatar = $params['avatar'];
                        }

                        if ($is_update_user) {
                            $student_user->save();
                        }
                    } else {
                        // 创建个新的用户
                        $student_user = model\User::createUser($params['number'], $params['name'], ['avatar' => $params['avatar'], 'gender' => $params['gender'], 'school_id' => $row['school_id']]);
                        if (isset($student_user['error'])) {
                            $this->error($student_user['error']);
                        }
                        $is_update_face = true;
                        $params['user_id'] = $student_user->id;
                    }

                    if ($is_update_face) {
                        $image = config('app_url') . $params['avatar'];
                        $image_type = 'URL';
                        $group_id = 'mp';
                        $user_id = $student_user->id;
                        $options = array();
                        $options["user_info"] = json_encode(['user_id' => $user_id, 'role' => 'student', 'student_id' =>  $row['id']]);
                        $options["action_type"] = "REPLACE";
                        $ret = AipFace::instance()->addUser($image, $image_type, $group_id, $user_id, $options);
                        if ($ret['error_code']) {
                            Db::rollback();
                            $this->error($ret['error_msg']);
                        }
                        \app\common\model\User::where('id', $user_id)->update(['face_token' => $ret['result']['face_token']]);
                    }

                    $result = $row->allowField(true)->save($params);

                    $class_student = model\ClassStudent::where('student_id', $ids)->find();
                    if ($class_student) {
                        $class_student->class_id = $params['class_id'];
                        $class_student->save();
                    } else {
                        $classStudent = new model\ClassStudent();
                        $classStudent->class_id = $params['class_id'];
                        $classStudent->student_id = $ids;
                        $classStudent->save();
                    }

                    $client = new Client([
                        'base_uri' => config('suzhi.url'),
                        'timeout' => 30,
                        'allow_redirects' => true
                    ]);
                    $response = $client->request('POST', '/platform/student/edit', [
                        'form_params' => [
                            'id' => $ids,
                            'name' => $params['name'],
                            'avatar' => config('app_url') . $params['avatar'],
                            'class_id' => $params['class_id'],
                            'parent_id' => $user->id,
                            'parent_mobile' => $user->mobile,
                            'parent_name' => $user->nickname,
                        ]
                    ]);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $schoolIds = $this->getDataLimitSchoolIds();
            if (is_array($schoolIds)) {
                $this->model->where($this->schoolLimitField, 'in', $schoolIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            Db::startTrans();
            try {
                $delete_ids = array_column($list, $pk);
                $delete_user_ids = array_column($list, 'user_id');

                $this->model->destroy($delete_ids);
                model\ClassStudent::whereIn('student_id', $delete_ids)->delete(false);
                model\User::destroy($delete_user_ids);

//                $this->model->whereIn('id', $delete_ids)->delete(false);
//                model\ClassStudent::whereIn('student_id', $delete_ids)->delete(false);
//                model\User::whereIn('id', $delete_user_ids)->delete(false);

                $client = new Client([
                    'base_uri' => config('suzhi.url'),
                    'timeout' => 30,
                    'allow_redirects' => true
                ]);
                $response = $client->request('POST', '/platform/student/del', [
                    'form_params' => [
                        'ids' => $delete_ids,
                    ]
                ]);
                $status = $response->getStatusCode();

                //Http::sendAsyncRequest(config('suzhi.url') . '/platform/student/del', ['ids' => $delete_ids]);

                Db::commit();

                $this->success();

            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

            $this->error(__('No rows were deleted'));
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 下载模板
     */
    public function download()
    {
        $file_path = 'template/批量导入模板.xlsx';
        $file_dir = ROOT_PATH . 'public' . DS . 'uploads' . DS . "$file_path";    // 下载文件存放目录

        // 检查文件是否存在
        if (!file_exists($file_dir)) {
            $this->error('文件不存在');
        } else {
            // 打开文件
            $file1 = fopen($file_dir, "r");
            // 输入文件标签
            Header("Content-type: application/octet-stream");
            Header("Accept-Ranges: bytes");
            Header("Accept-Length:" . filesize($file_dir));
            Header("Content-Disposition: attachment;filename=批量导入模板.xlsx");
            ob_clean();     // 重点！！！
            flush();        // 重点！！！！可以清除文件中多余的路径名以及解决乱码的问题：
            //输出文件内容
            //读取文件内容并直接输出到浏览器
            echo fread($file1, filesize($file_dir));
            fclose($file1);
            exit();
        }
    }

    /**
     * 批量导入学生
     *
     * @return string|void
     * @throws Exception
     * @throws PDOException
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     * @throws \think\db\exception\BindParamException
     * @throws \think\exception\DbException
     */
    public function import()
    {
        if ($this->request->isAjax()) {

            $class_id = $this->request->request('class_id');
            if (!$class_id) {
                $this->error(__('请选择班级'));
            }

            $classes = model\Classes::get($class_id);
            if (!$classes) {
                $this->error(__('班级不存在'));
            }

            set_time_limit(0);
            ini_set('memory_limit', '512M');
            $file = $this->request->request('file');

            if (!$file) {
                $this->error(__('Parameter %s can not be empty', 'file'));
            }

            $filePath = ROOT_PATH . DS . 'public' . DS . $file;
            if (!is_file($filePath)) {
                $this->error(__('No results were found'));
            }
            //实例化reader
            $ext = pathinfo($filePath, PATHINFO_EXTENSION);
            if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
                $this->error(__('Unknown data format'));
            }
            if ($ext === 'csv') {
                $file = fopen($filePath, 'r');
                $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
                $fp = fopen($filePath, "w");
                $n = 0;
                while ($line = fgets($file)) {
                    $line = rtrim($line, "\n\r\0");
                    $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                    if ($encoding != 'utf-8') {
                        $line = mb_convert_encoding($line, 'utf-8', $encoding);
                    }
                    if ($n == 0 || preg_match('/^".*"$/', $line)) {
                        fwrite($fp, $line . "\n");
                    } else {
                        fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                    }
                    $n++;
                }
                fclose($file) || fclose($fp);

                $reader = new Csv();
            } elseif ($ext === 'xls') {
                $reader = new Xls();
            } else {
                $reader = new Xlsx();
            }

            //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
            $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

            $table = $this->model->getQuery()->getTable();
            $database = \think\Config::get('database.database');
            $fieldArr = [];
            $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
            foreach ($list as $k => $v) {
                if ($importHeadType == 'comment') {
                    $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
                } else {
                    $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
                }
            }

//            dd($fieldArr);

            //加载文件
            $insert = [];

            try {
                if (!$PHPExcel = $reader->load($filePath)) {
                    $this->error(__('Unknown data format'));
                }
                $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
                $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
                $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
                $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
                $fields = [];
                for ($currentRow = 2; $currentRow <= 2; $currentRow++) {
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        $fields[] = $val;
                    }
                }

                for ($currentRow = 3; $currentRow <= $allRow; $currentRow++) {
                    $values = [];
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        $values[] = is_null($val) ? '' : $val;
                    }
                    $row = [];
                    $temp = array_combine($fields, $values);

                    // 家长信息
                    $parents = [
                        'name' => @$temp['家长姓名'],
                        'mobile' => @$temp['家长电话'],
                        'school_id' => $classes->school_id,
                    ];

                    $address = @$temp['家庭地址'];
                    foreach ($temp as $k => $v) {
                        if ($k !== '' && $v && isset($fieldArr[$k])) {
                            switch ($fieldArr[$k]) {
                                case 'gender':
                                    // 性别
                                    $v = $this->gender($v);
                                    break;
                                case 'parents_id':
                                    // 家长信息
                                    $v = $this->parents($parents);
                                    break;
                                case 'nationality_id':
                                    // 国籍
                                    $v = $this->nationality($v);
                                    break;
                                case 'nation_id':
                                    // 民族
                                    $v = $this->nation($v);
                                    break;
                                case 'address_id':
                                    // 家庭地址
                                    $v = $this->address($v);
                                    break;
                                case 'political_appearance_id':
                                    // 政治面貌
                                    $v = $this->politicalAppearance($v);
                                    break;
                            }
                            $row[$fieldArr[$k]] = $v;
                        }
                    }

                    if ($row) {

                        if (isset($row['number']) && $row['number']) {
                            $row['class_id'] = $classes->id;
                            $row['grade_id'] = $classes->grade_id;
                            $row['school_id'] = $classes->school_id;
                            $row['status'] = model\Student::DISPLAY;

                            if (isset($row['name']) && $row['name']) {
                                $row['pinyin'] = Pinyin::get($row['name']);
                            }

                            if (isset($row['birthday']) && $row['birthday']) {
                                $row['birthday'] = date('Y-m-d', strtotime("+ " . $row['birthday'] . " days", strtotime('1900-01-01')));
                            }

                            $student = model\Student::where('number', $row['number'])->where('class_id', $classes->id)->count();
                            if ($student) {
                                $this->error($row['number'] . ' 学号已存在');
                            } else {
                                $user = model\User::where('username', $row['number'])->field('id')->find();
                                if (!$user) {
                                    $user = model\User::createUser($row['number'], $row['name'], ['gender' => $row['gender'] ? $row['gender'] : 1, 'school_id' => $classes->school_id]);
                                }
                            }

                            $row['user_id'] = $user->id;
                            $row['address'] = $address;
                            $insert[] = $row;
                        } else {
                            $this->error($row['name'] . ' 学号信息错误');
                        }

                    }
                }

            } catch (Exception $exception) {
                $this->error($exception->getMessage() ? $exception->getMessage() : '添加失败');
            }

            if (!$insert) {
                $this->error(__('No rows were updated'));
            }

            $client = new Client([
                'base_uri' => config('suzhi.url'),
                'timeout' => 30,
                'allow_redirects' => true
            ]);

            $limit = 500;
            $count = ceil(count($insert) / $limit);
            for ($i = 1; $i <= $count; $i++) {
                $offset = ($i - 1) * $limit;
                $data = array_slice($insert, $offset, $limit);

                // 启动事务
                Db::startTrans();
                try {

                    $result = $this->model->saveAll($data);

                    $class_student_data = [];
                    $post_data = [];
                    foreach ($result as $key => $value) {
                        $class_student_data[] = [
                            'student_id' => $value['id'],
                            'class_id' => $value['class_id'],
                        ];
                        $insert_data = [
                            'id' => $value['id'],
                            'name' => $value['name'],
                            'class_id' => $value['class_id'],
                        ];

                        if (isset($value['parents_id']) && $value['parents_id'] && $parents = cache($value['parents_id'])) {
                            $insert_data = array_merge($insert_data, [
                                'parent_id' => $parents['user_id'],
                                'parent_mobile' => $parents['user_mobile'],
                                'parent_name' => $parents['user_name'],
                            ]);
                        }

                        $post_data[] = $insert_data;
                    }
                    $classStudent = new model\ClassStudent();
                    $classStudent->saveAll($class_student_data);

                    $response = $client->request('POST', '/platform/student/batchAdd', [
                        'json' => [
                            'data' => $post_data,
                        ]
                    ]);
                    $response->getStatusCode();
                    /*$body = $response->getBody();
                    if ($body->getSize()) {
                        $contents = $body->getContents();
                        dd($contents);
                    }*/

                    // 提交事务
                    Db::commit();
                } catch (PDOException $exception) {

                    // 回滚事务
                    Db::rollback();

                    $msg = $exception->getMessage();
                    if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                        $msg = "导入失败，学号【{$matches[1]}】已存在";
                    };

                    //SQLSTATE[42S22]: Column not found: 1054 Unknown column 'name' in 'where clause'

                    $this->error($msg ? $msg : '添加失败');
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $this->error($e->getMessage() ? $e->getMessage() : __('添加失败'));
                }
            }

            $this->success();
        }

        return $this->view->fetch();

    }

    // 性别
    private function gender($v)
    {
        return $v == '男' ? 1 : 0;
    }

    // 家长信息
    private function parents($data)
    {
        if (!$data || !isset($data['name']) || !$data['name']) return 0;

        if (isset($data['mobile']) && $data['mobile']) {
            $user = model\User::getUser($data['mobile'], $data['name'], ['school_id' => $this->auth->school_id]);
            if ($user) {
                $parents = model\Parents::where('user_id', $user->id)->find();
                if ($parents) {

                    cache($parents['id'], [
                        'user_id' => $user->id,
                        'user_name' => $user->nickname,
                        'user_mobile' => $user->mobile,
                    ], 300);

                    return $parents['id'];
                } else {
                    $parents = new model\Parents;
                    $parents->data([
                        'user_id' => $user->id,
                        'school_id' => $data['school_id'],
                    ]);
                    $parents->save();

                    cache($parents->id, [
                        'user_id' => $user->id,
                        'user_name' => $user->nickname,
                        'user_mobile' => $user->mobile,
                    ], 300);

                    return $parents->id;
                }
            } else {
                return 0;
            }
        } else {
            return 0;
        }

    }

    // 民族
    private function nation($v)
    {
        if (!$v) return 0;

        $nation = model\Nation::where('name', $v)->find();
        if ($nation) {
            $nation_id = $nation['id'];
        } else {
            $nation = new model\Nation();
            $nation->name = $v;
            $nation->save();

            $nation_id = $nation->id;
        }

        return $nation_id;
    }

    // 民族
    private function nationality($v)
    {
        if (!$v) return 0;

        $nationality = model\Nationality::where('name', $v)->find();
        if ($nationality) {
            $nationality_id = $nationality['id'];
        } else {
            $nationality = new model\Nationality();
            $nationality->name = $v;
            $nationality->save();

            $nationality_id = $nationality->id;
        }

        return $nationality_id;
    }

    // 家庭地址
    private function address($v)
    {
        if (!$v) return 0;

        $DistinguishAddress = new DistinguishAddress();
        $address = $DistinguishAddress->getAddressResult($v, false);

        $address_id = 0;
        if ($address) {
            $data['province_id'] = isset($address['province']) ? $address['province']['id'] : 0;
            $data['city_id'] = isset($address['city']) ? $address['city']['id'] : 0;
            $data['district_id'] = isset($address['district']) ? $address['district']['id'] : 0;
            $data['detail'] = isset($address['detail']) ? $address['detail'] : '';

            if ($data['province_id'] && $data['city_id'] && $data['district_id'] && $data['detail']) {
                $address = model\Address::where($data)->find();
                if ($address) {
                    $address_id = $address['id'];
                } else {
                    $address = new model\Address;
                    $address->data($data);
                    $address->save();
                    $address_id = $address->id;
                }
            }
        }

        return $address_id;
    }

    // 政治面貌
    private function politicalAppearance($v)
    {
        if (!$v) return 0;

        $politicalAppearance = model\PoliticalAppearance::get(['name' => $v]);
        if ($politicalAppearance) {
            $political_appearance_id = $politicalAppearance['id'];
        } else {
            $politicalAppearance = new model\PoliticalAppearance;
            $politicalAppearance->name = $v;
            $politicalAppearance->save();

            $political_appearance_id = $politicalAppearance->id;
        }
        return $political_appearance_id;
    }

    private function user($number, $name, $extend = [])
    {
        $count = model\User::where('username', $number)->count();
        if ($count) {
            return ['error' => '学号已存在'];
        }
        return model\User::createUser($number, $name, $extend);
    }
}
